package org.lanlab.storode.controller;

import org.lanlab.storode.common.CommonResult;
import org.lanlab.storode.dal.entity.Requirement;
import org.lanlab.storode.service.RequirementService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author dove
 * @since 2020/1/9 11:56
 */
@RestController
@RequestMapping("/requirements")
public class RequirementController {

    private final RequirementService requirementService;

    public RequirementController(RequirementService requirementService) {
        this.requirementService = requirementService;
    }

    @GetMapping
    public CommonResult<List<Requirement>> listAllRequirements() {
        List<Requirement> requirements = requirementService.listAllRequirements();
        return CommonResult.success(requirements);
    }

    @GetMapping("/no/{no}")
    public CommonResult<Requirement> getRequirementByNo(@PathVariable String no) {
        Requirement requirement = requirementService.getRequirementByNo(no);
        if (Objects.isNull(requirement)) {
            return CommonResult.failed("No such requirement");
        } else {
            return CommonResult.success(requirement);
        }
    }

    @PostMapping
    public CommonResult<String> addRequirement(@RequestBody Requirement requirement) {
        requirement = requirementService.insertRequirement(requirement);
        if (Objects.isNull(requirement.getId())) {
            return CommonResult.failed();
        } else {
            return CommonResult.success("requirement added successfully");
        }
    }

    @PutMapping("/no/{no}")
    public CommonResult<String> updateRequirement(@PathVariable String no,
                                                  @RequestBody Requirement requirement) {
        requirement.setRequirementNo(no);
        return requirementService.updateRequirement(requirement) ? CommonResult.success("Update successfully") : CommonResult.failed("Update failed");
    }

    @DeleteMapping("/no/{no}")
    public CommonResult<String> deleteRequirement(@PathVariable String no) {
        return requirementService.deleteRequirement(no) ? CommonResult.success("Delete successfully") : CommonResult.failed("Delete failed");
    }

}
